#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : fileapi.py
@TIME          : 2024/11/20 19:50:27
@AUTHOR        : chenlip
@VERSION       : 0.0.1
@DESCRIPTION   : 文件操作API, 使用flask-restx实现
'''
# --------------------------引用--------------------------
import os, sys, json
from flask import Blueprint, render_template
from flask import request
from flask_restx import Api, Resource, fields

from app.common.utils import Utils as ut
# --------------------------引用--------------------------

fileapi = Blueprint('fileapi', __name__ , url_prefix='/api/v1')
fnapi = Api(fileapi, version='1.0', title='文件操作API', description='文件操作API', doc='/doc')
# 名称空间
ns = fnapi.namespace('fileapi', description='文件操作API')

# --------------------------模型--------------------------
filemodel = fnapi.model('FileModel', {
    'filename': fields.String(required=True, description='文件名'),
    'content': fields.String(required=True, description='文件内容')
})

# --------------------------模型--------------------------

# --------------------------路由--------------------------
@ns.route('/savemdfile')
@fnapi.doc('文件操作API', responses={200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error'})
@fnapi.expect(filemodel)
class FileAPI(Resource):
    def post(self):
        '''
        文件操作API, 保存Markdown文件
        :Usage:
            POST /api/v1/fileapi/savemdfile
            前端使用javascript的fetch API发送POST请求, 请求头Content-Type: application/json, 请求体为json格式, 如下:
            {
                "filename": "文件名",
                "content": "文件内容"
            }
            JavaScript代码示例:
            fetch('/api/v1/fileapi/savemdfile', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "filename": "文件名",
                    "content": "文件内容"
                })
            }).then(response => response.json()).then(data => {
                console.log(data);
            });
        '''
        # 默认保存路径
        _path = os.path.join(ut.APPLICATION_ROOT, 'static', 'mdsave')
        if not os.path.exists(_path):
            os.makedirs
        
        try:
            _data = request.json
            _filename = _data['filename'] if _data['filename'] else ut.CURDAY+'-mdfile.md'
            _content = _data['content']
            _mdfile = os.path.join(_path, _filename)
            with open(_mdfile, 'w', encoding='utf-8') as f:
                f.write(_content)
            return {'status': 'OK'}
        except Exception as e:
            print(ut.cco('Error: '+str(e)))
            return {'status': 'Error', 'message': str(e)}
# --------------------------路由--------------------------

